<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学期" prop="semeId">
        <el-select v-model="queryParams.semeId" placeholder="请选择学期" :style="{width: '100%'}" @change="getUserGroup()">
          <el-option v-for="(item, index) in semeOptions" :key="index" :label="item.value"
                     :value="item.key" :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分党校" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择分党校" filterable  @change="getUserGroup()"
                   :style="{width: '100%'}" >
          <el-option v-for="(item, index) in deptOptions" :key="index" :label="item.value"
                     :value="item.key" :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['psedu-base:group:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 添加或修改小组对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-row :gutter="5"  v-loading="allLoading">
      <el-col :md="12">
        <el-card style=" padding-bottom: 20px">
          <div slot="header" class="clearfix">
            <span>待分配学员</span>
          </div>
          <draggable style="min-height: 100px;" v-model="waitUserList" group="people" @start="drag=true" @end="drag=false" v-bind="dragOptions">
            <el-col :lg="6" :xs="12" :sm="12" :md="8" v-for="student in waitUserList" :key="student.applyId">
              <el-card>
                <div class="card-user-tail">
                 {{student.realName}}
                  <span class="edubackground">{{student.eduBackground}}</span>
                </div>
                <el-divider></el-divider>
                <div class="student-classes">{{student.classes}}</div>
              </el-card>
            </el-col>
          </draggable>
        </el-card>
      </el-col>
      <el-col :md="12">
        <el-row :gutter="5">
          <el-card style="padding-bottom: 20px"
                   v-for="(groupStudent, index) in groupStudentList"
                   :key="groupStudent.groupId"
                   v-loading="loading">
            <div slot="header" class="clearfix">
              <span>{{groupStudent.groupName}}</span>
              <el-button @click="handlerDivideGroup(index)">保存</el-button>
              <el-button @click="handlerDeleteGroup(index)">删除</el-button>
            </div>
            <draggable style="min-height: 100px;"  v-model="groupStudent.studentList" group="people" @start="drag=true" @end="drag=false" v-bind="dragOptions">
              <el-col :lg="6" :xs="12" :sm="12" :md="8" v-for="student in groupStudent.studentList" :key="student.applyId">
                <el-card>
                  <div class="card-user-tail">
                    {{student.realName}}
                    <span class="edubackground">{{student.eduBackground}}</span>
                  </div>
                  <el-divider></el-divider>
                  <div class="student-classes">{{student.classes}}</div>
                </el-card>
              </el-col>
            </draggable>
          </el-card>
        </el-row>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import { listGroup, getGroup, delGroup, addGroup, updateGroup, userGroup } from "@/api/psedu-base/group";
import { divideGroup }  from "@/api/psedu-base/apply";
import { listSimpleSemester } from "@/api/psedu-base/semester"
import draggable from 'vuedraggable'
// import DeptSelect from "../componens/DeptSelect";
import { psDeptList } from "@/api/system/dept"
import { semeAndPsDeptOption } from "@/api/psedu-base/selectOption"

export default {
  name: "Group",
  components: {
    draggable
  },
  computed: {
    dragOptions() {
      return {
        animation: 200,
        group: "description",
        disabled: false,
        ghostClass: "ghost"
      };
    }
  },
  data() {
    return {
      semeOptions: [],
      deptOptions: [],
      // 遮罩层
      loading: false,
      allLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小组表格数据
      groupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        semeId: null,
        deptId: null,
        groupName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        semeId: [
          { required: true, message: "所属学期不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "所属分党校不能为空", trigger: "blur" }
        ],
      },
      waitUserList: [],
      groupStudentList: [
      ],
    };
  },
  created() {
    this.init()
  },
  methods: {

    init() {
      this.getSemeAndPsDeptOption().then(res => {
        this.getUserGroup();
      });
    },
    getSemeAndPsDeptOption() {
      console.log('--------')
      return semeAndPsDeptOption().then(res => {
        this.deptOptions = res.data.deptList;
        this.semeOptions = res.data.semeList;
        this.queryParams.deptId = this.deptOptions[0].key
        this.queryParams.semeId = this.semeOptions[0].key
        return Promise.resolve();
      })
    },
    getUserGroup() {
      this.allLoading = true
      return userGroup(this.queryParams.semeId, this.queryParams.deptId).then(resp => {
        this.waitUserList = resp.data.waitUserList;
        this.groupStudentList = resp.data.groupStudentList;
        this.allLoading = false;
        return Promise.resolve('success');
      })
    },
    // TODO 手拉琴
    handlerDivideGroup(index) {
      let groupStudent = this.groupStudentList[index];
      this.loading = true;
      console.log(this.loading)
      let groupId = groupStudent.groupId;
      let applyIds = groupStudent.studentList.map(student => student.applyId);
      divideGroup(groupId, applyIds).then(res => {
        this.$message.success("修改成功");
        this.loading = false;
        console.log(this.loading)
      }).catch(err => {
        this.$message.error("修改失败");
        this.loading = false;
      })
    },
    handlerDeleteGroup(index) {
      const groupIds = this.groupStudentList[index].groupId;
      this.$modal.confirm('是否确认删除小组编号为"' + groupIds + '"的数据项？').then(function() {
        return delGroup(groupIds);
      }).then(() => {
        this.getUserGroup();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        groupId: null,
        semeId: null,
        deptId: null,
        groupName: null,
        createTime: null,
        createBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getUserGroup()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.groupId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加小组";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const groupId = row.groupId || this.ids
      getGroup(groupId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改小组";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.groupId != null) {
            updateGroup(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getUserGroup()
            });
          } else {
            this.form.semeId = this.queryParams.semeId;
            this.form.deptId = this.queryParams.deptId;
            addGroup(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getUserGroup()
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const groupIds = row.groupId || this.ids;
      this.$modal.confirm('是否确认删除小组编号为"' + groupIds + '"的数据项？').then(function() {
        return delGroup(groupIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
<style scoped>
  .card-user-tail {
    text-align: center;
    font-size: 16px;
    line-height: 20px;
    font-weight: 700;
    position: relative;

  }
  .edubackground {
    color: #09c;
    position: absolute;
    top: -3px;
    right: -7px;
    font-size: 12px;
    line-height: 20px;
  }
  .student-classes {
    color: #c00;
    font-size: 18px;
    text-align: center;
  }
  /deep/ .el-divider--horizontal {
    margin: 8px 0;
  }
</style>
